import axios from 'axios'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 180000, // 请求超时时间
  customCode: false // 用与自定义判断code码状态
})

// 异常拦截处理器
const errorHandler = (error) => {
  console.log(error)
  if (error.response) {
    notification.error({
      message: '请求发生错误',
      description: `错误码：${error.response.status}`
    })
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use((config) => {
  if (config['setJson']) {
    config.headers['Content-Type'] = 'application/json'
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  const config = response.config
  if (response.data.code && response.data.code !== 200 && !config.customCode && response.data.code !== 201) {
    notification.error({
      message: '请求发生了错误',
      description: `${response.data.msg}。错误码：${response.data.code}`
    })
    return Promise.reject(new Error(response.data.msg || 'Error'))
  }
  return response.data
}, errorHandler)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export { installer as VueAxios, request as axios }
